import Decimal from 'decimal.js';
import { limitStrLength } from '@/utils';
import { isObject } from '@/utils/is';

/**
 * 格式化金额格式
 * @param amount
 * @returns
 */
export const formatAmt = (amount: number) => {
  if (!amount && typeof amount !== 'number') return amount;
  return new Intl.NumberFormat().format(amount);
};

/**
 * 将数字转为比例小数
 * @param num
 * @returns
 */
export const numberToRate = (num: any, digit?: number) => {
  if (!num && typeof num !== 'number') return num;
  if (typeof digit === 'number') {
    return Number(Decimal.div(num, 100).toFixed(digit));
  } else {
    return Decimal.div(num, 100).toNumber();
  }
};

/**
 * 将比例小数转为数字
 * @param rate
 * @param digit
 * @returns
 */
export const rateToNumber = (rate: any, digit?: number) => {
  if (!rate && typeof rate !== 'number') return rate;
  if (typeof digit === 'number') {
    return Number(Decimal.mul(rate, 100).toFixed(digit));
  } else {
    return Decimal.mul(rate, 100).toNumber();
  }
};

/**
 * 转换比例
 * @param {*} val
 * @param {*} symbol
 * @returns
 */
export function formatNumToRate(val: any, symbol = '%') {
  if (typeof val === 'number' || !isNaN(Number(val))) {
    return Decimal.mul(val || 0, 100).toString() + symbol;
  }
  return '-';
}

/**
 * 用于将mg/g转为kg，如果单位是kg/t或其他，则不变
 * @param weight
 * @param weightUnit
 * @param digit
 * @returns
 */
export const transitionUnitToKg = (weight: string | number, weightUnit: string, digit = 10) => {
  let transitionRatio = 1000;
  switch (weightUnit) {
    case 'mg':
      transitionRatio = 100000;
      break;
    case 'g':
      transitionRatio = 1000;
      break;
    default:
      return {
        weight,
        weightUnit
      };
  }
  const resW = limitStrLength(Decimal.div(weight, transitionRatio).toNumber(), digit);
  return {
    weight: resW,
    weightUnit: 'kg'
  };
};

/**
 * 过滤空字符串
 * @param obj
 * @returns
 */
export const objFilterEmptyString = (obj: { [key: string]: any }) => {
  if (isObject(obj)) {
    const newObj = Object.entries(obj).reduce((newObj: { [key: string]: any }, [key, value]) => {
      if (value !== '') {
        newObj[key] = value;
      }
      return newObj;
    }, {});
    return newObj;
  } else {
    return {};
  }
};
